package com.jd.controller;

import com.jd.exception.BussiException;
import com.jd.pojo.Member;
import com.jd.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MemberController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/register.html")
    public ModelAndView showRegister(){
        return new ModelAndView("/register");
    }

    @RequestMapping("/registe")
    @ResponseBody
    public Map registe(String vc, String username, String password, String nickname, HttpServletRequest request){
        String code = (String) request.getSession().getAttribute("kaptchaVerifyCode");
        Map map=new HashMap();
        if(vc==null||code==null||!vc.equalsIgnoreCase(code)){
            map.put("code","vc01");
            map.put("msg","验证码错误");
        }else{
            try{
                memberService.createMember(username,password,nickname);
                map.put("code","0");
                map.put("msg","success");
            }catch (BussiException ex){
                ex.printStackTrace();
                map.put("code",ex.getCode());
                map.put("msg",ex.getMsg());
            }
        }
        return map;
    }

    @RequestMapping("/check_login")
    @ResponseBody
    public Map checkLogin(String vc,String username,String password,HttpServletRequest request){
        String code = (String) request.getSession().getAttribute("kaptchaVerifyCode");
        Map map=new HashMap();
        if(vc==null||code==null||!vc.equalsIgnoreCase(code)){
            map.put("code","vc01");
            map.put("msg","验证码错误");
        }else{
            try {
                Member member = memberService.checkLogin(username, password);
                request.getSession().setAttribute("checkLogin",member);
                map.put("code","0");
                map.put("msg","success");
            }catch (BussiException ex){
                ex.printStackTrace();
                map.put("code",ex.getCode());
                map.put("msg",ex.getMsg());
            }

        }
        return map;
    }

    @GetMapping("/login.html")
    public ModelAndView showLogin(){
        return new ModelAndView("/loginPage");
    }

}
